<?php
/**
 * Created by PhpStorm.
 * User: yuanjie
 * Date: 15/10/20
 * Time: 下午5:03
 */
class SceOrderController extends BaseController {

    /**
     * @Author   lyt                      <ahlyt@anhuibj.com>
     * @DateTime 2017-11-03T09:24:11+0800
     * @return   [type]                   [description]
     * 技师端燃油加注
     */
    public function filling_smy(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'code' => 'required',
                // "number"=>"required"
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');
            $code = Input::get('code');
            $number=Input::get("number",0);

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){                
                break;
            }
            
            OrderSmyFilling::where("order_id",$order_id)->where("code",$code)->update(array("filling_number"=>$number,"filling_date"=>date("Y-m-d",time()),"filling_by"=>$engineer_data->id));

            $result = array(
                'order_id' => $order_id,
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"model" => "order", "event" => "filling_smy", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /*
     * 修改维修状态
     * */
    public function update_exception_detection(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'detection' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');
            $desc = Input::get('desc');
            $detection = json_decode(Input::get('detection'));

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }

            foreach ($detection as $_detection){
                OrderDetection::where('id',$_detection->id)->where('order_id',$order_id)->update(array('status' => $_detection->status));
            }
            OrderDetectionDesc::where("order_id",$order_id)->update(array("note"=>$desc));

            $result = array(
                'order_id' => $order_id,
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"model" => "order", "event" => "update_exception_detection", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /*
     * 获取检测报告异常项目
     * */
    public function get_exception_detection(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get("order_id");
            $status = Input::get("status")?Input::get("status"):'';

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }
            if($status == ''){
                $de=OrderDetection::where("order_id",$order_id)->where("level",1)->orderBy("sort","asc")->select("id","order_id","name","c_name","parent_id","dt_id","level","amount","c_desc","fraction","status","sort")->get();
                $exception=array();
                foreach ($de as $_de) {
                    $_de->amount=$_de->amount/100;
                    $two_de=OrderDetection::where("order_id",$order_id)->where("parent_id",$_de->id)->where("level",2)->select("id","order_id","name","c_name","parent_id","dt_id","level","amount","c_desc","fraction","status","sort")->orderBy("sort","asc")->get();
                    foreach ($two_de as $_t_de) {
                        $_t_de->amount=$_t_de->amount/100;
                        if($_t_de->status != 0){//说明异常了
                            $temp= clone $_t_de;
                            $two_temp=OrderDetection::where("order_id",$order_id)->where("parent_id",$_t_de->id)->where("level",3)->where("status",1)->select("id","order_id","name","c_name","parent_id","dt_id","level","amount","c_desc","fraction","status","sort")->orderBy("sort","asc")->get();
                            foreach ($two_temp as $value) {
                                $value->amount=$value->amount/100;
                            }
                            $temp->item_arr=$two_temp;
                            $exception[]=$temp;
                        }
//                    $two_temp2=OrderDetection::where("order_id",$order_id)->where("parent_id",$_t_de->id)->where("level",3)->select("id","order_id","name","c_name","parent_id","dt_id","level","amount","c_desc","fraction","status","sort")->orderBy("sort","asc")->get();
//                    foreach ($two_temp2 as $value) {
//                        $value->amount=$value->amount/100;
//                    }
//                    $_t_de->item_arr=$two_temp2;
                    }
//                $_de->item_arr=$two_de;
                }
            }else{
                $de=OrderDetection::where("order_id",$order_id)->where("level",1)->orderBy("sort","asc")->select("id","order_id","name","c_name","parent_id","dt_id","level","amount","c_desc","fraction","status","sort")->get();
                $exception=array();
                foreach ($de as $_de) {
                    $_de->amount=$_de->amount/100;
                    $two_de=OrderDetection::where("order_id",$order_id)->where("parent_id",$_de->id)->where("level",2)->select("id","order_id","name","c_name","parent_id","dt_id","level","amount","c_desc","fraction","status","sort")->orderBy("sort","asc")->get();
                    foreach ($two_de as $_t_de) {
                        $_t_de->amount=$_t_de->amount/100;
                        if($_t_de->status == $status){
                            $temp= clone $_t_de;
                            $two_temp=OrderDetection::where("order_id",$order_id)->where("parent_id",$_t_de->id)->where("level",3)->where("status",1)->select("id","order_id","name","c_name","parent_id","dt_id","level","amount","c_desc","fraction","status","sort")->orderBy("sort","asc")->get();
                            foreach ($two_temp as $value) {
                                $value->amount=$value->amount/100;
                            }
                            $temp->item_arr=$two_temp;
                            $exception[]=$temp;
                        }
//                    $two_temp2=OrderDetection::where("order_id",$order_id)->where("parent_id",$_t_de->id)->where("level",3)->select("id","order_id","name","c_name","parent_id","dt_id","level","amount","c_desc","fraction","status","sort")->orderBy("sort","asc")->get();
//                    foreach ($two_temp2 as $value) {
//                        $value->amount=$value->amount/100;
//                    }
//                    $_t_de->item_arr=$two_temp2;
                    }
//                $_de->item_arr=$two_de;
                }
            }

            $order = Orders::where('order_id',$order_id)->first();
            $engineer = MaintenanceEngineers::where('id',$order->engineer_id)->first();
            $desc = OrderDetectionDesc::where('order_id',$order_id)->select('note')->first();
            if(is_null($desc)) $desc = ''; else $desc = $desc->note;
            $result = array(
                'order_id' => $order_id,
                'car_no' => $order->car_no,
                'car_brand_name' => $order->car_brand_name,
                'car_series_name' => $order->car_series_name,
                'car_model_name' => $order->car_model_name,
                'engineer' => $engineer->name,
                'desc' => $desc,
                'exception' => $exception
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"model" => "order", "event" => "get_exception_detection", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:    2017-02-23 10:26:55
     * @Description: 新的 检测信息模板
     */
    public function get_detection(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }
            $one_array=$two_array=$three_array=array();
            $de=OrderDetection::where("order_id",$order_id)->where("status",1)->select("dt_id","level")->get();//获取所有异常项
            foreach ($de as  $_de) {
                switch ($_de->level) {
                    case 1:
                        $one_array[]=$_de->dt_id;
                        break;
                    case 2:
                        $two_array[]=$_de->dt_id;
                        break;
                    case 3:
                        $three_array[]=$_de->dt_id;
                        break;                    
                }
            }
            $de=DetectionTemplate::where("level",1)->where("status",1)->orderBy("sort","asc")->get();
            foreach ($de as $_de) {
                $_de->status=in_array($_de->id,$one_array)?1:0;
                $two_de=DetectionTemplate::where("parent_id",$_de->id)->where("level",2)->where("status",1)->orderBy("sort","asc")->get();
                foreach ($two_de as $_t_de) {
                    $_t_de->status=in_array($_t_de->id,$two_array)?1:0;
                    $three_de=DetectionTemplate::where("parent_id",$_t_de->id)->where("level",3)->where("status",1)->orderBy("sort","asc")->get();
                    foreach ($three_de as $_thr_de) {
                        $_thr_de->status=in_array($_thr_de->id,$three_array)?1:0;
                    }
                    $_t_de->item_arr=$three_de;
                }
                $_de->item_arr=$two_de;
            }           
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("info"=>$de));
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "get_detection", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:    2017-02-23 13:02:56
     * @Description: 获取新建的检测项目增值服务
     */
    public function get_detection_product(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }
            $orders=Orders::find($order_id);
            if(is_null($orders)){
                $response = Lang::get("sce_error.order_notexiet_1012");
                break;
            }
            $t_odi=array();
            $odi=OrderDetectionIncrement::where("order_id",$order_id)->where("status",1)->select("di_id")->get();
            foreach ($odi as $_odi) {
                $t_odi[]=$_odi->di_id;
            }
            $odc=OrderDetectionDesc::where("order_id",$order_id)->first();

            $de=DetectionIncrement::where("status",1)->orderBy("sort","asc")->get();
            foreach ($de as $_de) {
                $_de->status=in_array($_de->id,$t_odi)?1:0;
            }
            $odd =OrderDetectionDesc::leftJoin("maintenance_engineers as me1","order_detection_desc.create_by","=","me1.id")->leftJoin("maintenance_engineers as me2","order_detection_desc.auth_by","=","me2.id")->select("order_detection_desc.note","order_detection_desc.create_by","me1.name as create_name","order_detection_desc.auth_by","me2.name as auth_name","order_detection_desc.created_at")->where("order_detection_desc.order_id",$order_id)->first();
            $order_info=array("car_brand_id"=>$orders->car_brand_id,"car_brand_name"=>$orders->car_brand_name,"car_series_id"=>$orders->car_series_id,"car_series_name"=>$orders->car_series_name,"car_model_id"=>$orders->car_model_id,"car_model_name"=>$orders->car_model_name,"mileage"=>$orders->mileage);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("info"=>$de,"desc"=>isset($odc)?$odc->note:'',"check_desc"=>isset($odd)?$odd:(object)null,"order_info"=>$order_info));
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "get_detection_product", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:    2017-02-23 11:45:58
     * @Description: 保存检测报告
     */
    public function save_detection(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'check' => 'required',//id 和status 的数组 转换的josn 
                'auditor_account' => 'required',
                'auditor_pwd' => 'required',
                'product'=>"required",//id  的数组 转换的josn 
                //"desc"=>"required",
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                $response["result"]=$validator->messages()->all();
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id'); //订单ID
            $check = json_decode(Input::get('check'));
            $auditor_account = Input::get('auditor_account');
            $auditor_pwd = Input::get('auditor_pwd');
            $product = json_decode(Input::get('product'));
            $desc = Input::get('desc');
            $new_product=array();
            foreach($product as $_product){
                $new_product[(int)$_product->id]=$_product->status;
            }

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }
            $auditor = MaintenanceEngineers::where('account',$auditor_account)
                ->where('passwd',md5($auditor_pwd))
                ->where('status',1)
                ->where('type_id',$engineer_data->type_id)
                ->first();
            if(is_null($auditor)){
                $response = Lang::get("sce_error.login_not_exist_error_1002");
                break;
            }
            if(!in_array($auditor->title,array(1,2))){
                $response = Lang::get("sce_error.login_error_1022");
                break;
            }

            $orders=Orders::find($order_id);
            if(is_null($orders)){
                $response = Lang::get("sce_error.order_notexiet_1012");
                break;
            }
            if($orders->shop_id!=$engineer_data->type_id){
                $response = Lang::get("sce_error.order_note_shop_error_1013");
                break;
            }
            if($orders->status != 1215){
                $response = Lang::get("sce_error.order_status_error_1019");
                break;
            }
            try {
                
                /*
                *检测提交项目 构建保存结构
                 */
                //查出所有的 项目 构成 一级-二级-三级 id为键值 状态为值的数组
                $finally=array();
                foreach ($check as $dt) {
                    $res=DB::select("SELECT dt3.id dt3_id,dt3.name dt3_name,dt3.c_name dt3_c_name,dt3.c_desc dt3_c_desc,dt3.fraction dt3_fraction,dt3.sort dt3_sort,
                        dt2.id dt2_id,dt2.name dt2_name,dt2.c_name dt2_c_name,dt2.c_desc dt2_c_desc,dt2.fraction dt2_fraction,dt2.sort dt2_sort,
                        dt1.id dt1_id,dt1.name dt1_name,dt1.c_name dt1_c_name,dt1.c_desc dt1_c_desc,dt1.fraction dt1_fraction,dt1.sort dt1_sort 
                        FROM `detection_template` dt3   
                        LEFT JOIN `detection_template` dt2 on dt3.parent_id=dt2.id   
                        LEFT JOIN `detection_template` dt1 on dt2.parent_id=dt1.id  where dt3.id=? and dt3.`level`=3",array($dt->id));
                    if(!isset($res[0])){
                        $response = Lang::get("sce_error.detection_error_2000");
                        break 2;
                    }
                    $finally[$res[0]->dt1_id.'-'.$res[0]->dt2_id.'-'.$res[0]->dt3_id]=array("status"=>$dt->status);
                }
                //查出所有的 项目 检测提交的是不是现在所有的项目
                $de=DetectionTemplate::where("level",1)->where("status",1)->select("id","name","c_name","c_desc","fraction","sort")->get();
                foreach ($de as $_de) {
                    $_de->check_status=0;//默认检测正常
                    $two_de=DetectionTemplate::where("parent_id",$_de->id)->where("level",2)->where("status",1)->select("id","name","c_name","c_desc","fraction","sort")->get();
                    foreach ($two_de as $_t_de) {
                        $_t_de->check_status=0;//默认检测正常
                        $temp_de=DetectionTemplate::where("parent_id",$_t_de->id)->where("level",3)->where("status",1)->select("id","name","c_name","c_desc","fraction","sort")->get();
                        foreach ($temp_de as $_three_temp_de) {
                            if(isset($finally[$_de->id."-".$_t_de->id."-".$_three_temp_de->id])){
                                $_three_temp_de->check_status=$finally[$_de->id."-".$_t_de->id."-".$_three_temp_de->id]["status"];
                                if($_three_temp_de->check_status!=0){
                                    $_de->check_status=$_three_temp_de->check_status;
                                    $_t_de->check_status=$_three_temp_de->check_status;
                                }
                            }else{
                                $response = Lang::get("sce_error.detection_error_2000");
                                break 4;
                            }
                        }
                        $_t_de->item_arr=$temp_de;
                    }
                    $_de->item_arr=$two_de;
                }  

                //构造提交的的增值项目
                
                $di=DetectionIncrement::where("status",1)->select("id","name","sort")->get();




                foreach ($di as $_di) {
                    // if(in_array($_di->id, $new_product)){
                    //     $_di->check_status=1;
                    // }else{
                    //     $_di->check_status=0;
                    // }
                    if(isset($new_product[$_di->id])){
                        $_di->check_status=$new_product[$_di->id];
                    }else{
                        $response = Lang::get("sce_error.detection_error_2000");
                        break 2;
                    }
                }

                /*
                *检测提交项目 构建保存结构结束
                 */
                /**
                 * 保存 检测报告传入 检测项 检测增值项 和用户信息
                 */
                $response=OrderDetection::savedate($de,$di,$engineer_data,$auditor,$order_id,$desc);
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "save_30_check", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.order_cancel_error_1008");
                break;
            }
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "save_detection", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


   /**
    * @Author:      lyt
    * @DateTime:    2017-02-23 15:38:20
    * @Description: 获取订单的新版的检测记录
    */
    public function get_order_detection(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id=Input::get("order_id");
            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }
            $orders=Orders::find($order_id);
            if(is_null($orders)){
                $response = Lang::get("sce_error.order_notexiet_1012");
                break;
            }
            if($orders->shop_id!=$engineer_data->type_id){
                $response = Lang::get("sce_error.order_note_shop_error_1013");
                break;
            }
            $de=OrderDetection::getOrderDetection($order_id); 
            $order_info=array("car_brand_id"=>$orders->car_brand_id,"car_brand_name"=>$orders->car_brand_name,"car_series_id"=>$orders->car_series_id,"car_series_name"=>$orders->car_series_name,"car_model_id"=>$orders->car_model_id,"car_model_name"=>$orders->car_model_name,"mileage"=>$orders->mileage);         
            $de["order_info"]=$order_info;
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $de);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "get_order_detection", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /*
     * 保存30项检测信息
     * */
    public function save_30_check(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'check' => 'required',
                'auditor_account' => 'required',
                'auditor_pwd' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id'); //订单ID
            $check = json_decode(Input::get('check'));
            $auditor_account = Input::get('auditor_account');
            $auditor_pwd = Input::get('auditor_pwd');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }
            $auditor = MaintenanceEngineers::where('account',$auditor_account)
                ->where('passwd',md5($auditor_pwd))
                ->where('status',1)
                ->where('type_id',$engineer_data->type_id)
                ->first();
            if(is_null($auditor)){
                $response = Lang::get("sce_error.login_not_exist_error_1002");
                break;
            }

            try {
                if(sizeof($check)>70){
                    $response = Lang::get("sce_error.save_30_check_error_1023");
                    break;
                }
                Order30Check::where('order_id',$order_id)->delete();
                foreach($check as $item){
                    foreach(Order30Check::$check as $default){
                        if($default['item_id'] == $item->id){
//                            $order_30_check = Order30Check::firstOrNew(array('order_id' => $order_id,'object_id' => $default['object_id'] ,'item_id' =>$item->id));
                            $order_30_check = new Order30Check();
                            $order_30_check->order_id = $order_id;
                            $order_30_check->object_id = $default['object_id'];
                            $order_30_check->item_id = $item->id;
                            $order_30_check->object_name = $default['object_name'];
                            $order_30_check->item_name = $item->name;
                            $order_30_check->value = $item->value;
                            $order_30_check->status = $item->status;
                            $order_30_check->note = $item->note;
                            $order_30_check->save();
                        }
                    }
                }
                // $o3c_pdf_url=Config::get('config.pdf_url');
                // PDF::loadFile('http://www.github.com')->setPaper('a4')->setOrientation('landscape')->setOption('margin-bottom', 0)->save('myfile.pdf');
                // $pt=PrintTask::where('order_id',$order_id)->first();
                // if(!$pt){
                //     $pt=new PrintTask;
                //     $pt->order_id=$order_id;
                //     $pt->shop_id=$engineer_data->type_id;
                //     $pt->url=$url;
                //     $pt->save();
                // }

                $result = array(
                    'order_id' => $order_id
                );
                $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "save_30_check", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.order_cancel_error_1008");
                break;
            }
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "save_30_check", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:    2017-02-15 11:35:11
     * @Description: 修改 30项检测 打印
     */
    public function save_30_check_print(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'check' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id'); //订单ID
            $check = json_decode(Input::get('check'));
            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }
           

            try {
                if(sizeof($check)>70){
                    $response = Lang::get("sce_error.save_30_check_error_1023");
                    break;
                }
                Order30Check::where('order_id',$order_id)->delete();
                foreach($check as $item){
                    foreach(Order30Check::$check as $default){
                        if($default['item_id'] == $item->id){
//                            $order_30_check = Order30Check::firstOrNew(array('order_id' => $order_id,'object_id' => $default['object_id'] ,'item_id' =>$item->id));
                            $order_30_check = new Order30Check();
                            $order_30_check->order_id = $order_id;
                            $order_30_check->object_id = $default['object_id'];
                            $order_30_check->item_id = $item->id;
                            $order_30_check->object_name = $default['object_name'];
                            $order_30_check->item_name = $item->name;
                            $order_30_check->value = $item->value;
                            $order_30_check->status = $item->status;
                            $order_30_check->note = $item->note;
                            $order_30_check->save();
                        }
                    }
                }
                $o3c_pdf_url=Config::get('config.pdf_url')."order_id=".$order_id;
                $pdf_name= Common::getPdfName();
                // PDF::loadFile($o3c_pdf_url)->setPaper('a4')->setOrientation('landscape')->setOption('margin-bottom', 0)->save(Config::get('config.pdf_file').$pdf_name);
                // $pt=PrintTask::where('order_id',$order_id)->first();
                // if(!$pt){
                    $pt=new PrintTask;
                    $pt->order_id=$order_id;
                    $pt->shop_id=$engineer_data->type_id;
                    $pt->url=$pdf_name;
                    $pt->save();
                // }

                $result = array(
                    'order_id' => $order_id
                );
                $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "save_30_check", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.order_cancel_error_1008");
                break;
            }
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "save_30_check_print", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }



    /*
     * 获取30项检测信息
     * */
    public function get_30_check(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id'); //订单ID

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }
            $four_wheel_check = Order30Check::get_four_wheel_check($order_id);
            $cab_check = Order30Check::get_cab_check($order_id);
            $light_check = Order30Check::get_light_check($order_id);
            $engine_room_check = Order30Check::get_engine_room_check($order_id);
            $chassis_check = Order30Check::get_chassis_check($order_id);
            $general_suggest = Order30Check::get_general_suggest($order_id);
            $check = array();
            array_push($check,$four_wheel_check);
            array_push($check,$cab_check);
            array_push($check,$light_check);
            array_push($check,$engine_room_check);
            array_push($check,$chassis_check);
            array_push($check,$general_suggest);
            $result = array(
                'order_id' => $order_id,
                'check' => $check
            );
//            $result = array(
//                'four_wheel_check' => $four_wheel_check,
//                'cab_check' => $cab_check,
//                'light_check' => $light_check,
//                'engine_room_check' => $engine_room_check,
//                'chassis_check' => $chassis_check,
//                'general_suggest' => $general_suggest,
//            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "get_30_check", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 获取环检信息
     * */
    public function get_ring_check(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id'); //订单ID

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }
            $order_ring_check = OrderRingCheck::where('order_id',$order_id)
                ->select(array('sound','cigarette_lighter','front_mark','tire_cover','rear_mark','axle_cover','antenna','fire_extinguisher','fuel','mile','note','pic'))
                ->first();
            if(is_null($order_ring_check)){
                $result = array(
                    'order_id' => $order_id,
                    'sound' => 0,
                    'cigarette_lighter' => 0,
                    'front_mark' => 0,
                    'tire_cover' => 0,
                    'rear_mark' => 0,
                    'axle_cover' => 0,
                    'antenna' => 0,
                    'fire_extinguisher' => 0,
                    'fuel' => 0,
                    'mile' => 0,
                    'note' => '',
                    'pic' => ''
                );
            }else{
                $path=Config::get('config.ring_check_img_url');
                $result = array(
                    'order_id' => $order_id,
                    'sound' => $order_ring_check->sound,
                    'cigarette_lighter' => $order_ring_check->cigarette_lighter,
                    'front_mark' => $order_ring_check->front_mark,
                    'tire_cover' => $order_ring_check->tire_cover,
                    'rear_mark' => $order_ring_check->rear_mark,
                    'axle_cover' => $order_ring_check->axle_cover,
                    'antenna' => $order_ring_check->antenna,
                    'fire_extinguisher' => $order_ring_check->fire_extinguisher,
                    'fuel' => $order_ring_check->fuel,
                    'mile' => $order_ring_check->mile,
                    'note' => $order_ring_check->note,
                    'pic' => $path.$order_ring_check->pic
                );
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "get_ring_check", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 保存订单环检信息
     * */
    public function save_ring_check(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id'); //订单ID
            $sound = Input::get('sound')?Input::get('sound'):0; //音响
            $cigarette_lighter = Input::get('cigarette_lighter')?Input::get('cigarette_lighter'):0; //点烟器
            $front_mark = Input::get('front_mark')?Input::get('front_mark'):0; //前标
            $tire_cover = Input::get('tire_cover')?Input::get('tire_cover'):0; //轮盖
            $rear_mark = Input::get('rear_mark')?Input::get('rear_mark'):0; //后标
            $axle_cover = Input::get('axle_cover')?Input::get('axle_cover'):0; //轴头饰盖
            $antenna = Input::get('antenna')?Input::get('antenna'):0; //天线
            $fire_extinguisher = Input::get('fire_extinguisher')?Input::get('fire_extinguisher'):0; //灭烟器
            $fuel = Input::get('fuel')?Input::get('fuel'):0; //燃油
            $mile = Input::get('mile')?Input::get('mile'):0; //里程
            $note = Input::get('note')?Input::get('note'):null; //备注
            $pic = Input::get('pic')?Input::get('pic'):null; //环检图

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }

            try {
                $order_ring_check['sound'] = $sound;
                $order_ring_check['cigarette_lighter'] = $cigarette_lighter;
                $order_ring_check['front_mark'] = $front_mark;
                $order_ring_check['tire_cover'] = $tire_cover;
                $order_ring_check['rear_mark'] = $rear_mark;
                $order_ring_check['axle_cover'] = $axle_cover;
                $order_ring_check['antenna'] = $antenna;
                $order_ring_check['fire_extinguisher'] = $fire_extinguisher;
                $order_ring_check['fuel'] = $fuel;
                $order_ring_check['mile'] = $mile;
                $order_ring_check['note'] = $note;
                if($pic){
                    $pic_name = date("YmdHis", time()) . rand(10000, 99999) . '.png';
                    $img = base64_decode($pic);
                    $path=Config::get('config.ring_check_file');
                    File::put( $path . $pic_name, $img);
                    $order_ring_check['pic'] = $pic_name;
                }

                $count = OrderRingCheck::where('order_id',$order_id)->count();
                if($count > 0){ //存在
                    OrderRingCheck::where('order_id',$order_id)
                        ->update($order_ring_check);
                }else{ //不存在
                    $order_ring_check['order_id'] = $order_id;
                    OrderRingCheck::insert($order_ring_check);
                }

                $result = array(
                    'order_id' => $order_id
                );
                $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "save_ring_check", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.order_status_error_1011");
                break;
            }
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "save_ring_check", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 待选技师
     * */
    public function get_engineer_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'shop' => 'required'
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $shop = Input::get('shop');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }

            $engineers = MaintenanceEngineers::where('type','shop')
                ->where('type_id',$shop)
                ->where('status',1)
                ->select(array('id','name'))
                ->get()->toArray();
            $count = count($engineers);
            $result = array(
                'count' => $count,
                'engineers'=> $engineers
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "get_engineer_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 更换技师验证
     * */
    public function change_engineer_check(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'product_id' => 'required',
                'select_engineer_id' => 'required',
//                'auditor_account' => 'required',
//                'auditor_pwd' => 'required',
                // 'order_product_id' => 'required',
                // 'type' => 'required'
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');
            $product_id = Input::get('product_id');
            $select_engineer_id = Input::get('select_engineer_id');
            $auditor_account = Input::get('auditor_account');
            $auditor_pwd = Input::get('auditor_pwd');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }

            //验证主管
//            $auditor = MaintenanceEngineers::where('account',$auditor_account)
//                ->where('passwd',md5($auditor_pwd))
//                ->where('status',1)
//                ->first();
//            if(!is_null($auditor)){
                try {
                    $order_service_engineers = new OrderServiceEngineers();
                    $order_service_engineers->order_id = $order_id;
                    $order_service_engineers->product_id = $product_id;
                    $order_service_engineers->engineer_id = $select_engineer_id;
                    $order_service_engineers->engineer_type	 = 'assist';
//                    $order_service_engineers->auditor_id = $auditor->id;
                    $order_service_engineers->auditor_id = 0;
                    $order_service_engineers->created_at = Common::num2DateTime(time());
                    $order_service_engineers->updated_at = Common::num2DateTime(time());
                    $order_service_engineers->save();

                    $op = OrderProduct::find($product_id);
                    $op->engineer_id = $select_engineer_id;
                    $op->save();

                    if($op->product_type=='promotion'){
                        // $opp=OrderProductPackage::find(Input::get('order_product_id'));
                        // $opp->engineer_id=$select_engineer_id;
                        // $opp->save();
                        OrderProductPackage::where("order_product_id",$op->id)->update(array("engineer_id"=>$select_engineer_id));
                    }elseif($op->product_type=='enterprise'){
                        // $opep=OrderProductEsPackage::find(Input::get('order_product_id'));
                        // $opep->engineer_id=$select_engineer_id;
                        // $opep->save();
                        OrderProductEsPackage::where("order_product_id",$op->id)->update(array("engineer_id"=>$select_engineer_id));
                    }elseif($op->product_type=='activity'){
                        // $opacp=OrderProductAcPackage::find(Input::get('order_product_id'));
                        // $opacp->engineer_id=$select_engineer_id;
                        // $opacp->save();
                        OrderProductAcPackage::where("order_product_id",$op->id)->update(array("engineer_id"=>$select_engineer_id));
                    }

                    $result = array(
                        'order_id' => $order_id,
                    );
                    $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
                } catch (Exception $e) {
                    Log::error("error", array("system" => "sce" ,"event" => "change_engineer_check", 'input' =>Input::all() ,"exception" => $e));
                    $response = Lang::get("sce_error.order_cancel_error_1008");
                    break;
                }
//            }else{
//                $response = Lang::get("sce_error.user_not_exist_1021");
//                break;
//            }
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "change_engineer_check", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 复检验证
     * */
    public function order_recheck(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'auditor_account' => 'required',
                'auditor_pwd' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');
            $auditor_account = Input::get('auditor_account');
            $auditor_pwd = Input::get('auditor_pwd');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }            
            $orders=Orders::find($order_id);
            if(is_null($orders)){
                $response = Lang::get("sce_error.order_notexiet_1012");
                break;
            }
            if($orders->shop_id!=$engineer_data->type_id){
                $response = Lang::get("sce_error.order_note_shop_error_1013");
                break;
            }
            if($orders->status != 1215){
                $response = Lang::get("sce_error.order_status_error_1019");
                break;
            }
            // if($orders->shop_id==1){
            //     $osf=OrderSmyFilling::where("order_id",$order_id)->where("status",1)->where("filling_number",0)->first();
            //     if($osf){
            //         $response = Lang::get("sce_error.order_filling_1025");
            //         break;
            //     }
            // }
           
            if(!MaintenanceOutOrder::isAllOut($orders->order_id)){//是否有 没有出入库记录的耗材
                $response = Lang::get("scs_error.order_out_return_notexit_40035");
                break;
            }
            if(Orders::isOutReturnOrders($orders->order_id)){//是否有 未完成的出退库 记录
                $response = Lang::get("scs_error.order_out_return_error_40034");
                break;
            }

            //验证主管
            $auditor = MaintenanceEngineers::where('account',$auditor_account)
                ->where('passwd',md5($auditor_pwd))
                ->where('status',1)
                ->where('type_id',$engineer_data->type_id)
                ->whereIn('title',array(1,2))
                ->first();
            if(!is_null($auditor)){
                try {
                    $orders->status=Config::get('order.engineer_service_end_order_status');
                    $orders->end_time=Common::num2DateTime(time());
                    $orders->save();

                    $order_flows = new OrderFlows;
                    $order_flows->order_id = $order_id;
                    $order_flows->status = Config::get('order.engineer_service_end_order_status');
                    $order_flows->type = 'engineer';
                    $order_flows->user_id = $auditor->id;
                    $order_flows->created_at = Common::num2DateTime(time());
                    $order_flows->save();

                    //工位占用详细信息入库(结束时间)
                    try {
                        $station_start_time = MaintenanceStationDetails::UpdatedDetails($order_id,$engineer_data->type_id);
                    }catch(Exception $e){
                        Log::error("error", array("system" => "scs" ,"event" => "UpdatedDetails", 'input' =>Input::all() ,"exception" => $e));
                    }


                    //清除这个订单的停车场数据  
                    MaintenancePark::where('order_id',$order_id)->delete();

                    $mp = new MaintenancePark();
                    $mp->shop_id=$engineer_data->type_id;
                    $mp->order_id=$order_id;
                    $mp->status=1;
                    $mp->user_id=$engineer_data->id;
                    $mp->save();

                    $mscs=MaintenanceStationCarStatus::where('order_id',Input::get('order_id'))->update(array("car_no"=>"","status"=>0,"car_model_id"=>0,"order_id"=>0,'mileage'=>0,'vin_code'=>'','insurance'=>''));

                    $result = array(
                        'order_id' => $order_id,
                    );
//                    if(is_null($station_start_time)){
//                        $response = Lang::get("sce_error.station_car_start_time_exiet_1001");
//                        break;
//                    }

                    $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
                } catch (Exception $e) {
                    Log::error("error", array("system" => "sce" ,"event" => "order_recheck", 'input' =>Input::all() ,"exception" => $e));
                    $response = Lang::get("sce_error.order_cancel_error_1008");
                    break;
                }
            }else{
                $response = Lang::get("sce_error.user_not_exist_1021");
                break;
            }

            //推送微信信息
            $wechat_user=Users::find($orders->user_id);
            if(isset($wechat_user)&&$wechat_user->openid){
                $templateId = Config::get('config.scs_order_start_templateId');
                $url = Config::get('config.redirect_url').'/order/show?is_wash=0&order_id='.$orders->order_id;
                $data = array(
                    "first"  => "亲爱的车主您好，你的爱车服务进度已更新。",
                    "keyword1" =>  $orders->car_no,
                    "keyword2"   => "保养/维修",
                    "keyword3"   => "服务完成待结算",
                    "remark" => "请点击查看详细检测记录"
                );
                try {
                    WechatOauthController::sendMessage($wechat_user->openid, $templateId, $data, $url);
                }catch(Exception $e){
                    Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                }
            }
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "order_recheck", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zy
     * @DateTime:    2017-09-15 
     * @Description: 当前门店主管列表
     */
    public function manager_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                break;
            }

            $managers = MaintenanceEngineers::where('status',1)->whereIn('title',array(1,2))
                    ->where('type_id',$engineer_data->type_id)
                    ->select("id","name","phone","account","photo")
                    ->get();

            if(!empty($managers)){
                $engineers_photo_url = Config::get('config.engineers_photo_url');
                foreach($managers as &$r){
                    $r->photo = empty($r->photo) ? "1505973628-31980.png": $r->photo;
                    $r->photo = $engineers_photo_url.$r->photo;
                }
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $managers);
            
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "manager_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      lyt
     * @DateTime:    2016-05-26 12:09:17
     * @Description: 用于验证耗材是否都出库了
     */
    public function order_supply_recheck(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>Input::get('order_id')));
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }
            $orders=Orders::find($order_id);
            if(is_null($orders)){
                $response = Lang::get("sce_error.order_notexiet_1012");
                break;
            }
            if($orders->shop_id!=$engineer_data->type_id){
                $response = Lang::get("sce_error.order_note_shop_error_1013");
                break;
            }
            // if($orders->shop_id==1){
            //     $osf=OrderSmyFilling::where("order_id",$order_id)->where("status",1)->where("filling_number",0)->first();
            //     if($osf){
            //         $response = Lang::get("sce_error.order_filling_1025");
            //         break;
            //     }
            // }            
            if(!MaintenanceOutOrder::isAllOut($orders->order_id)){//是否有 没有出入库记录的耗材
                $response = Lang::get("scs_error.order_out_return_notexit_40035");
                break;
            }
            if(Orders::isOutReturnOrders($orders->order_id)){//是否有 未完成的出退库 记录
                $response = Lang::get("scs_error.order_out_return_error_40034");
                break;
            }
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "order_supply_recheck", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 创建订单
     * 技师创建订单，只生成基本的订单号，通过确认用户，确认车辆，30项检测，产品添加等补充其他信息。
     * */
    public function create(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }
            if($engineer_data->type == 'shop'){
                $shop_id = $engineer_data->type_id;
                $car_id = 0;
            }else{
                $car_id = $engineer_data->type_id;
                $car_data = MaintenanceCars::where('id',$car_id)->where('status',1)->first();
                $shop_id = $car_data->shop_id;
            }
            $shop_data = MaintenanceShops::where('id',$shop_id)
                ->where('status',1)
                ->first();

            try {
                $order_id = Common::createOrderId();
                $order = new Orders;
                $order->order_id = $order_id;
                $order->city = $shop_data->city;
                $order->book_time = Common::num2DateTime(time());
                $order->shop_id = $shop_data->id;
                $order->car_id = $car_id;
                $order->status = Config::get('order.engineer_create_order_status');
                $order->created_at = Common::num2DateTime(time());
                //默认值
                $order->order_source = 12;
                $order->place = 2;
                $order->tittle = '';
                $order->pay_type = 0;
                $order->user_car_id = 0;
                $order->note = '';
                $order->car_no = '';
                $order->save();

                $order_flows = new OrderFlows;
                $order_flows->order_id = $order_id;
                $order_flows->status = Config::get('order.engineer_create_order_status');
                $order_flows->type = 'engineer';
                $order_flows->user_id = $engineer_data->id;
                $order_flows->created_at = Common::num2DateTime(time());
                $order_flows->save();

            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "create", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.order_create_error_1007");
                break;
            }
            $result = array(
                'order_id' => $order_id,
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "search", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 取消订单
     * 技师在订单没有确认之前可以取消
     * */
    public function cancel(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }
            try {
                //查询最新状态
                $order_flows = OrderFlows::where('order_id',$order_id)->orderBy('updated_at', 'desc')->first();
                if($order_flows->status == Config::get('order.engineer_create_order_status')){
                    //更新订单表
                    Orders::where('order_id',$order_id)->update(array('status' => Config::get('order.engineer_cancel_order_status')));

                    //订单流转表新增记录
                    $order_flows = new OrderFlows;
                    $order_flows->order_id = $order_id;
                    $order_flows->status = Config::get('order.engineer_cancel_order_status');
                    $order_flows->user_id = $engineer_data->id;
                    $order_flows->type = 'engineer';
                    $order_flows->created_at = Common::num2DateTime(time());
                    $order_flows->save();
                }else{
                    $response = Lang::get("sce_error.order_cancel_error_1008");
                    break;
                }
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "cancel", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.order_cancel_error_1008");
                break;
            }
            $result = array(
                'order_id' => $order_id,
                'status' => Config::get('order.engineer_cancel_order_status')
            );

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "cancel", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 更新订单－用户信息确认－订单开始服务
     * insert update
     * 技师确认用户则订单确认并开始，如果已经确认则开始。
     * */
    public function update_user_info(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'user_name' => 'required',
                'user_phone' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');
            $user_name = Input::get('user_name');
            $user_phone = Input::get('user_phone');
            $user_id = Input::get('user_id')?Input::get('user_id'):0;

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }

            try{
                //用户信息 insert update
                if($user_id != 0){ //用户存在
                    Users::where('id',$user_id)->where('status',1)->update(
                        array(
                            'real_name' => $user_name,
                            'phone' => $user_phone
                        )
                    );
                }else{
                    $user = Users::where('phone',$user_phone)->where('status',1)->first();
                    if(!is_null($user)){
                        Users::where('phone',$user_phone)->update(
                            array(
                                'real_name' => $user_name,
                            )
                        );
                        $user_id = $user->id;
                    }else{
                        $user_id = Users::insertGetId(
                            array(
                                'real_name' => $user_name,
                                'phone' => $user_phone,
                                'status' => Config::get('user.user_normal_status'),
                                'register_source_id' => Config::get('user.user_source_engineer'),
                                'area' => Config::get('user.user_default_area'),
                                'created_at' => Common::num2DateTime(time()),
                                'updated_at' => Common::num2DateTime(time())
                            )
                        );
                    }
                }

//                //订单为新建则为首次订单确认，否则仅为订单用户修改
//                $order = Orders::where('order_id',$order_id)->select(array('status'))->first();
//                if($order->status == Config::get('order.engineer_create_order_status')){
//                    //更新订单流转
//                    OrderFlows::insert(array(
//                        'order_id' => $order_id,
//                        'status' => Config::get('order.engineer_confirm_order_status'),
//                        'user_id' => $engineer_data->id,
//                        'type' => 'engineer',
//                        'created_at' => Common::num2DateTime(time()),
//                        'updated_at' => Common::num2DateTime(time()),
//                    ));
//
//                    OrderFlows::insert(array(
//                        'order_id' => $order_id,
//                        'status' => Config::get('order.engineer_service_begin_order_status'),
//                        'user_id' => $engineer_data->id,
//                        'type' => 'engineer',
//                        'created_at' => Common::num2DateTime(time()),
//                        'updated_at' => Common::num2DateTime(time()),
//                    ));
//
//                    $order_status = Config::get('order.engineer_service_begin_order_status');
//                }elseif($order->status == Config::get('order.service_confirm_order_status')) {
//                    OrderFlows::insert(array(
//                        'order_id' => $order_id,
//                        'status' => Config::get('order.engineer_service_begin_order_status'),
//                        'user_id' => $engineer_data->id,
//                        'type' => 'engineer',
//                        'created_at' => Common::num2DateTime(time()),
//                        'updated_at' => Common::num2DateTime(time()),
//                    ));
//
//                    $order_status = Config::get('order.engineer_service_begin_order_status');
//                }else{
//                    $order_status = $order->status;
//                }

                //订单信息 update
                Orders::where('order_id',$order_id)->update(
                    array(
                        'user_id' => $user_id,
                        'name' => $user_name,
                        'phone' => $user_phone,
//                        'status' => $order_status
                    )
                );

                $result = array(
                    'order_id' => $order_id,
                    'user_id' => $user_id,
//                    'status' => $order_status
                );
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "update_user_info", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.order_update_error_1009");
                break;
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "update_user_info", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 更新订单－车辆信息
     * */
    public function update_car_info(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'user_id' => 'required',
//                'user_car_id' => 'required',
                'brand_id' => 'required',
                'series_id' => 'required',
                'model_year' => 'required',
                'model_gear_box' => 'required',
                'model_gas_rate' => 'required',
                'vin_code' => 'required',
                'mileage' => 'required',
                'oil_meter' => 'required',
                'car_no' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');
            $user_id = Input::get('user_id');
            $brand_id = Input::get('brand_id');
            $series_id = Input::get('series_id');
            $model_year = Input::get('model_year');
            $model_gear_box = Input::get('model_gear_box');
            $model_gas_rate = Input::get('model_gas_rate');
            $vin_code = strtoupper(Input::get('vin_code'));
            $mileage = Input::get('mileage');
            $oil_meter = Input::get('oil_meter');
            $car_no = strtoupper(Input::get('car_no'));
            $user_car_id = Input::get('user_car_id')?Input::get('user_car_id'):0;

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }

            try{
                //获得车型代码
                $car_module = DataCarStandardInfo::where('brand_name_id',$brand_id)
                    ->where('series_name_id',$series_id)
                    ->where('model_year',$model_year)
                    ->where('model_gear_box',$model_gear_box)
                    ->where('model_gas_rate',$model_gas_rate)
                    ->select('id')
                    ->first();
                if(is_null($car_module)){
                    $car_module_id = 0;
                }else{
                    $car_module_id = $car_module->id;
                }

                //用户车辆数据insert update
                if($user_car_id != 0){ //用户车型ID存在，更新用户车型信息并认证
                    UserCarInfo::where('id',$user_car_id)
                        ->where('user_id',$user_id)
                        ->where('status',1)
                        ->update(array(
                            'car_brand_id' => $brand_id,
                            'car_series_id' => $series_id,
                            'car_model_id' => $car_module_id,
                            'is_lock' => 1,
                            'car_no' => $car_no,
                            'vin_code' => $vin_code,
                            'mileage' => $mileage
                        ));
                }else{
                    $user_car_id = UserCarInfo::insertGetId(
                        array(
                            'user_id' => $user_id,
                            'status' => 1,
                            'car_brand_id' => $brand_id,
                            'car_series_id' => $series_id,
                            'car_model_id' => $car_module_id,
                            'is_lock' => 1,
                            'car_no' => $car_no,
                            'vin_code' => $vin_code,
                            'mileage' => $mileage,
                            'created_at' => Common::num2DateTime(time()),
                            'updated_at' => Common::num2DateTime(time())
                        )
                    );
                }

                //订单为新建则为首次订单确认，否则仅为订单用户修改
                $order = Orders::where('order_id',$order_id)->select(array('status'))->first();
                if($order->status == Config::get('order.engineer_create_order_status')){
                    //更新订单流转
                    OrderFlows::insert(array(
                        'order_id' => $order_id,
                        'status' => Config::get('order.engineer_confirm_order_status'),
                        'user_id' => $engineer_data->id,
                        'type' => 'engineer',
                        'created_at' => Common::num2DateTime(time()),
                        'updated_at' => Common::num2DateTime(time()),
                    ));

                    OrderFlows::insert(array(
                        'order_id' => $order_id,
                        'status' => Config::get('order.engineer_service_begin_order_status'),
                        'user_id' => $engineer_data->id,
                        'type' => 'engineer',
                        'created_at' => Common::num2DateTime(time()),
                        'updated_at' => Common::num2DateTime(time()),
                    ));

                    $order_status = Config::get('order.engineer_service_begin_order_status');
                }elseif($order->status == Config::get('order.service_confirm_order_status')) {
                    OrderFlows::insert(array(
                        'order_id' => $order_id,
                        'status' => Config::get('order.engineer_service_begin_order_status'),
                        'user_id' => $engineer_data->id,
                        'type' => 'engineer',
                        'created_at' => Common::num2DateTime(time()),
                        'updated_at' => Common::num2DateTime(time()),
                    ));

                    $order_status = Config::get('order.engineer_service_begin_order_status');
                }else{
                    $order_status = $order->status;
                }
                //更新订单信息
                Orders::where('order_id',$order_id)->update(
                    array(
                        'user_car_id' => $user_car_id,
                        'car_brand_id' => $brand_id,
                        'car_series_id' => $series_id,
                        'car_model_id' => $car_module_id,
                        'car_no' => $car_no,
                        'mileage' => $mileage,
                        'oil_meter' => $oil_meter,
                        'status' => $order_status
                    )
                );

                $result = array(
                    'order_id' => $order_id,
                    'user_car_id' => $user_car_id
                );
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "update_car_info", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.order_update_error_1009");
                break;
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "update_car_info", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 更新订单－检测信息
     * */
    public function update_check_info(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'report' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');
            $report = Input::get('report');
            $suggest = Input::get('suggest')?Input::get('suggest'):'';

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }

            try{
                $report_data = json_decode($report);
                foreach($report_data as $_report){
                    $order_check_report = OrderCheckReport::firstOrNew(array('order_id' => $order_id,'check_id' => $_report->check_id));
                    $order_check_report->status = $_report->status;
                    $order_check_report->note = $_report->note;
                    $order_check_report->save();
                }
                if($suggest != ''){
                    $suggest_data = json_decode($suggest);
                    foreach($suggest_data as $_suggest){
                        $order_check_suggest = OrderCheckSuggest::firstOrNew(array('order_id' => $order_id));
                        $order_check_suggest->content = $_suggest->content;
                        $order_check_suggest->save();
                    }
                }

                $result = array(
                    'order_id' => $order_id,
                );
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "update_check_info", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.order_update_error_1009");
                break;
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "update_check_info", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 订单检测报告查询
     * */
    public function search_check_info(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }
            $count = OrderCheckReport::where('order_id',$order_id)->count();
            if($count == 0){
                $report = array();
                $reports = CheckReport::where('status',1)->select(array('id','item'))->get()->toArray();
                foreach($reports as $_report){
                    $_report['status'] = 0;
                    $_report['note'] = '';
                    array_push($report,$_report);
                }
                $suggest = array();
            }else{
                //检测报告信息
                $report = OrderCheckReport::where('order_id',$order_id)->select(array('check_id as id','check_item as item','status','note'))->get()->toArray();
                //检测建议信息
                $suggest = OrderCheckSuggest::where('order_id',$order_id)->select(array('id','content'))->get()->toArray();
            }

            $result = array(
                'report' => $report,
                'suggest' => $suggest,
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "search_check_info", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 订单产品－查询
     * */
    public function search_product_info(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }
            $result = OrderProduct::getOrderProduct($order_id);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "search_product_info", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 新增产品
     * */
    public function add_product_info(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'type' => 'required',
                'product' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');
            $type = Input::get('type');
            $product = Input::get('product');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }

            try{
                $product = json_decode($product);
                //记录订单产品信息
                $order_product = new OrderProduct();
                $order_product->order_id = $order_id;
                $order_product->product_type = $type;
                $order_product->product_id = $product->product_id;
                $order_product->product_name = $product->product_name;
                $order_product->status = 1;
                $order_product->save();

                if($type == 'promotion' || $type == 'base') {
                    //记录产品包信息
                    $package = $product->packages;
                    foreach($package as $_package){
                        $order_product_package = new OrderProductPackage();
                        $order_product_package->order_id = $order_id;
                        $order_product_package->order_product_id = $order_product->id;
                        $order_product_package->package_id = $_package->package_id;
                        $order_product_package->package_name = $_package->package_name;
                        $order_product_package->work_station = -1;
                        $order_product_package->work_status = 'prepare';
                        $order_product_package->created_at = Common::num2DateTime(time());
                        $order_product_package->updated_at = Common::num2DateTime(time());
                        $order_product_package->save();

                        //记录产品项信息
                        $items = $_package->item;
                        foreach($items as $_item){
                            $order_product_item = new OrderProductItem();
                            $order_product_item->order_id = $order_id;
                            $order_product_item->order_product_package_id = $order_product_package->id;
                            $order_product_item->item_id = $_item->item_id;
                            $order_product_item->item_name = $_item->item_name;
                            $order_product_item->amount = $_item->amount;
                            $order_product_item->num = $_item->num;
                            $order_product_item->created_at = Common::num2DateTime(time());
                            $order_product_item->updated_at = Common::num2DateTime(time());
                            $order_product_item->save();
                        }
                    }
                }elseif($type == 'non_standard'){
                    //记录订单非标产品
                    $order_product_non_standard = new OrderProductNonStandard();
                    $order_product_non_standard->order_id = $order_id;
                    $order_product_non_standard->order_product_id = $order_product->id;
                    $order_product_non_standard->name = $product->product_name;
                    $order_product_non_standard->num = $product->num;
                    $order_product_non_standard->amount = $product->amount;
                    $order_product_non_standard->work_station = -1;
                    $order_product_non_standard->work_status = 'prepare';
                    $order_product_non_standard->created_at = Common::num2DateTime(time());
                    $order_product_non_standard->updated_at = Common::num2DateTime(time());
                    $order_product_non_standard->save();
                }

                $result = array(
                    'order_id' => $order_id,
                );
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "add_product_info", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.order_update_error_1009");
                break;
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "add_product_info", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 修改产品信息（增减数量和金额）
     * */
    public function change_product_info(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'type' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');
            $type = Input::get('type');
            $id = Input::get('id');
            $name = Input::get('name')?Input::get('name'):'';
            $num = Input::get('num')?Input::get('num'):-1;
            $amount = Input::get('amount')?Input::get('amount'):-1;
            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }
            $update = array();
            try{
                if($type == 'promotion' || $type == 'base') {
                    //基础和推广只修改数量
                    if($num != -1){
                        $update['num'] = $num;
                    }
                    OrderProductItem::where('id',$id)
                        ->where('order_id',$order_id)
                        ->update($update);
                }elseif($type == 'non_standard'){
                    //非标数量说明价格都可以修改
                    if($num != -1){
                        $update['num'] = $num;
                    }
                    if($amount != -1){
                        $update['amount'] = $amount;
                    }
                    if($name != ''){
                        $update['name'] = $name;
                    }

                    OrderProductNonStandard::where('id',$id)
                        ->where('order_id',$order_id)
                        ->where('status',1)
                        ->update($update);
                }
                $result = array(
                    'order_id' => $order_id,
                );
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "change_product_info", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.order_update_error_1009");
                break;
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "change_product_info", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 订单产品删除
     * */
    public function delete_product_info(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'type' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');
            $type = Input::get('type');
            $id = Input::get('id');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }

            try{
                if($type == 'non_standard'){
                    $order_product_non_standard = OrderProductNonStandard::where('id',$id)->where('status',1)->first();
                    $id = $order_product_non_standard->order_product_id;
                }
                OrderProduct::where('id',$id)
                    ->where('order_id',$order_id)
                    ->where('product_type',$type)
                    ->update(array('status' => 0));

                $result = array(
                    'order_id' => $order_id,
                );
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "delete_product_info", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.order_update_error_1009");
                break;
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "delete_product_info", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 订单流传记录
     * */
    public function insert_product_flows(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'type' => 'required',
                'product_id' => 'required',
                'work_station' => 'required',
                'work_status' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');
            $type = Input::get('type');
            $product_id = Input::get('product_id');
            $package_id = Input::get('package_id')?Input::get('package_id'):0;
            $work_station = Input::get('work_station');
            $work_status = Input::get('work_status');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }

            try{
                //记录流转表
                $order_product_flows = new OrderProductFlows();
                $order_product_flows->order_id = $order_id;
                $order_product_flows->type = $type;
                $order_product_flows->order_product_id = $product_id;
                $order_product_flows->order_product_package_id = $package_id;
                $order_product_flows->work_station = $work_station;
                $order_product_flows->work_status = $work_status;
                $order_product_flows->engineer_id = $engineer_data->id;
                $order_product_flows->created_at = Common::num2DateTime(time());
                $order_product_flows->updated_at = Common::num2DateTime(time());
                $order_product_flows->save();

                //更新产品信息
                if($type == 'promotion' || $type == 'base'){
                    OrderProductPackage::where('id',$package_id)
                        ->where('order_id',$order_id)
                        ->where('order_product_id',$product_id)
                        ->update(array(
                            'work_station' => $work_station,
                            'work_status' => $work_status,
                        ));
                }elseif($type == 'non_standard'){
                    OrderProductNonStandard::where('id',$product_id)
                        ->where('order_id',$order_id)
                        ->where('status',1)
                        ->update(array(
                            'work_station' => $work_station,
                            'work_status' => $work_status,
                        ));
                }
                $result = array(
                    'order_id' => $order_id,
                );
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "insert_product_flows", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.order_update_error_1009");
                break;
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "insert_product_flows", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 更新订单－产品信息
     * */
    public function update_product_info(){

    }

    /*
     * 更新订单－基础信息
     * */
    public function update_base_info(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');
            $note = Input::get('note')?Input::get('note'):'';
            $name = Input::get('name')?Input::get('name'):'';
            $phone = Input::get('phone')?Input::get('phone'):'';
            $oil_meter = Input::get('oil_meter')?Input::get('oil_meter'):0;
            $mileage = Input::get('mileage')?Input::get('mileage'):0;

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }

            try{
                //订单信息 update
                Orders::where('order_id',$order_id)->update(
                    array(
                        'note' => $note,
                        'name' => $name,
                        'phone' => $phone,
                        'oil_meter' => $oil_meter,
                        'mileage' => $mileage
                    )
                );

                $result = array(
                    'order_id' => $order_id,
                );
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "update_base_info", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.order_update_error_1009");
                break;
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "update_base_info", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 订单服务结束
     * */
    public function complete(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }

            try{
                $order = Orders::where('order_id',$order_id)->select(array('status'))->first();
                if($order->status != Config::get('order.engineer_service_begin_order_status')){
                    $response = Lang::get("sce_error.order_status_error_1010");
                    break;
                }else{
                    $order_status = Config::get('order.engineer_service_end_order_status');
                }
                //订单信息 update
                Orders::where('order_id',$order_id)->update(
                    array(
                        'status' => $order_status
                    )
                );

                //订单流转表新增记录
                $order_flows = new OrderFlows;
                $order_flows->order_id = $order_id;
                $order_flows->status = $order_status;
                $order_flows->user_id = $engineer_data->id;
                $order_flows->type = 'engineer';
                $order_flows->created_at = Common::num2DateTime(time());
                $order_flows->save();

                $result = array(
                    'order_id' => $order_id,
                    'status' => $order_status
                );
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "complete", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.order_update_error_1009");
                break;
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "complete", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 更新订单
     * */
    public function update(){

    }

    /*
     * 服务中订单
     * */
    public function servicing(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $limit = Input::get("limit", 10);
            $offset = Input::get("offset", 0);

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }
            $orders = Orders::where('engineer_id',$engineer_data->id)
                ->whereIn('status',array(1213,1214,1215))
                ->where('order_type',1)
                ->skip($offset)
                ->take($limit)
                ->select('order_id','name','tittle','phone','book_time','place','status','note','car_no','car_brand_name','car_series_name','car_model_name')
                ->orderBy('updated_at', 'desc')
                ->get()->toArray();

            $count = count($orders);
            $result = array(
                'count' => $count,
                'orders' => $orders
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "servicing", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /*
     * 查询车辆订单
     * */
    public function search(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'no' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $no = Input::get('no');
            $limit = Input::get("limit", 10);
            $offset = Input::get("offset", 0);

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }

            //暂时去除，只针对车牌。
//            //正则判断是车牌 or 订单号 or 手机号
//            if(preg_match("/^1[34578]\d{9}$/", $no)){ //手机号
//                $orders = Orders::join('users','orders.user_id','=','users.id')
//                    ->where('users.phone',$no)
//                    ->where('users.status',1)
//                    ->skip($offset)
//                    ->take($limit)
//                    ->select('orders.order_id','orders.name','orders.tittle','orders.phone','orders.book_time','orders.place','orders.status','orders.note')
//                    ->orderBy('orders.updated_at', 'desc')
//                    ->get()->toArray();
//            }elseif(preg_match("/[\x80-\xff]+[A-Z][0-9a-zA-Z]{5}/",$no)){ //车牌号
//                $orders = Orders::where('car_no',$no)
//                    ->skip($offset)
//                    ->take($limit)
//                    ->select('order_id','name','tittle','phone','book_time','place','status','note')
//                    ->orderBy('updated_at', 'desc')
//                    ->get()->toArray();
//            }else{ //订单号
//                $orders = Orders::where('order_id',$no)
//                    ->skip($offset)
//                    ->take($limit)
//                    ->select('order_id','name','tittle','phone','book_time','place','status','note')
//                    ->orderBy('updated_at', 'desc')
//                    ->get()->toArray();
//            }

            $orders = Orders::where('car_no',$no)
                ->where('order_type',1)
                ->where('shop_id',$engineer_data->type_id)
                ->skip($offset)
                ->take($limit)
                ->select('order_id','name','tittle','phone','book_time','place','status','note')
                ->orderBy('updated_at', 'desc')
                ->get()->toArray();

            $count = count($orders);
            $result = array(
                'count' => $count,
                'orders' => $orders
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "search", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * 订单详情
     * @link http://api.anhui.com/v1/sce/order/show?token=528a87425418084f8adb38dc5576f48d&order_id=15226558329029
     */
    public function show(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id'  => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');

            //验证token
            $engineer_data1 = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data1)){
                
                break;
            }
           
            //订单产品信息
            $order = Orders::where('order_id',$order_id)
                ->select(array('order_id','user_id','status','name','tittle','phone','book_time','book_hour','place','shop_id','address','note','amount','car_no','engineer_id','user_car_id','mileage','estimated_completion_time'))
                ->get()->toArray();
//            $products = OrderProduct::join('product_package','product_package.id','=','order_product.product_id')
//                ->where('order_product.order_id',$order_id)
//                ->where('order_product.status',1)
//                ->select(array('order_product.product_id','product_package.name','order_product.num','order_product.amount'))
//                ->orderBy("order_product.created_at", "desc")
//                ->get()->toArray();
            $engineer_data = MaintenanceEngineers::find($order[0]['engineer_id']);
            // $products = OrderProduct::getOrderProductForEngineer($order_id,$engineer_data);
            $products = OrderProduct::getOrderProductByIdEngin($order_id);
            $order_ids=Orders::where("car_no",$order[0]['car_no'])->whereIn("status",Orders::$complete)->select('order_id')->get()->toArray();
            //$orderProduct=OrderProduct::getOrderProductByOrderIds($order_ids);
            //$allHour=OrderProduct::getOrderHoursByOrderIds($order_ids);
            $order[0]['products'] = $products;
            //$order[0]['allItem'] = $orderProduct['allItem'];
            //$order[0]['allHour'] = $allHour;
            //用户信息
            $user = Users::where('id',$order[0]['user_id'])
                ->where('status',1)
                ->select(array('id','real_name as name','phone'))
                ->get()->toArray();
            //车辆信息
            $user_car_data = UserCarInfo::leftJoin('anhui_data.car_standard_info','anhui_data.car_standard_info.id','=','user_car_info.car_model_id')
                ->where('user_id',$order[0]['user_id'])
                ->where('car_no',$order[0]['car_no'])
                ->where('user_car_info.id',$order[0]['user_car_id'])
                ->where('user_car_info.status',1)
                ->select(array('user_car_info.id','model_name','brand_name','series_name','car_brand_id','car_series_id','car_model_id','car_no'))
                ->first();
            if(is_null($user_car_data)){
                $user_car = array();
            }else{
                $car_model = DataCarStandardInfo::where('id',$user_car_data->car_model_id)
                    ->select('model_year','model_gas_rate','model_gear_box')
                    ->first();
                if(is_null($car_model)){
                    $model_year = '';
                    $model_gas_rate = '';
                    $model_gear_box = '';
                }else{
                    $model_year = $car_model->model_year;
                    $model_gas_rate = $car_model->model_gas_rate;
                    $model_gear_box = $car_model->model_gear_box;
                }
                $user_car = array(
                    array(
                        'id' => $user_car_data->id,
                        'car_brand_id' => $user_car_data->car_brand_id,
                        'car_series_id' => $user_car_data->car_series_id,
                        'car_model_id' => $user_car_data->car_model_id,
                        'model_name' => $user_car_data->model_name,
                        'brand_name' => $user_car_data->brand_name,
                        'series_name'  => $user_car_data->series_name,
                        'car_no' => $user_car_data->car_no,
                        'year' => $model_year,
                        'gas_rate' => $model_gas_rate,
                        'gear_box' => $model_gear_box
                    ),
                );
            }

            //技师信息
            if($engineer_data->type == 'shop'){
                $shop = MaintenanceShops::where('id',$engineer_data->type_id)->first();
                $engineer = array(
                    'name' => $engineer_data->name,
                    'tittle' => $engineer_data->tittle,
                    'skill_level' => $engineer_data->skill_level,
                    'shop' => array(
                        'id' => $shop->id,
                        'city' => $shop->city_id,
                        'name' => $shop->name
                    ),
                    'car' => array()
                );
            }else{
                $car = MaintenanceCars::where('id',$engineer_data->type_id)->where('status',1)->first();
                $shop = MaintenanceShops::where('id',$car->shop_id)->where('status',1)->first();
                $engineer = array(
                    'name' => $engineer_data->name,
                    'tittle' => $engineer_data->tittle,
                    'skill_level' => $engineer_data->skill_level,
                    'shop' => array(
                        'id' => $shop->id,
                        'city' => $shop->city_id,
                        'name' => $shop->name
                    ),
                    'car' => array(
                        'id' => $car->id,
                        'no' => $car->car_no,
                        'name' => $car->car_name,
                    )
                );
            }
            //检测报告信息
            $report = OrderCheckReport::where('order_id',$order_id)->select(array('check_id as id','check_item as item','status','note'))->get()->toArray();
            //检测建议信息
            $suggest = OrderCheckSuggest::where('order_id',$order_id)->select(array('id','content'))->get()->toArray();
            $check = array(
                'report' => $report,
                'suggest' => $suggest,
            );
            //查询该订单的工位信息
            $station_info = MaintenanceStationCarStatus::where('order_id', $order_id)
                    ->select('shop_id', 'station_id', 'car_no', 'status', 'created_at')->first();
            if(is_null($station_info)){
                $station_status = 0;
            } else {
                $station_status = 1;    //工位状态 0:不存在工位信息;1:存在工位信息;
            }
            
            $result = array(
                'user' => $user,
                'car' => $user_car,
                'engineer' => $engineer,
                'check' => $check,
                'order' => $order,
                'station_status' => $station_status,
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);

        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "show", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2016-9-18 16:08:31
     * @Description: 维修记录
     */
    public function maintenanceRecord(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'car_no' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
         if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');

            //验证token
            $engineer_data1 = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data1)){
                
                break;
            }
            
            $order_ids=Orders::where("car_no",Input::get('car_no'))->whereIn("status",Orders::$complete)->where("pay_time",'>',"2016-01-01 00:00:00")->orderBy("pay_time","DESC")->take(10)->select('order_id')->get()->toArray();
            $orderProduct=OrderProduct::getOrderProductByOrderIds($order_ids);
            $allHour=OrderProduct::getOrderHoursByOrderIds($order_ids);
            $mr['allHour']=$allHour;
            $mr['allItem']=$orderProduct['allItem'];
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $mr);
        }while(false);
        Log::info("info", array("system" => "sce" ,"event" => "maintenanceRecord", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /*
     * 更新车辆保险到期日
     * */
    public function update_insurance_date(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'date' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }
    
            //传入参数
            $order_id = Input::get('order_id');
            $token = Input::get('token');
    
            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }
    
            try{
                $orders=Orders::find($order_id);
                if(is_null($orders)){
                    $response = Lang::get("sce_error.order_notexiet_1012");
                    break;
                }
                $uci=UserCarInfo::find($orders->user_car_id);
                $uci->insurance=Input::get('date');
                $uci->save();
                $result = array(
                    'order_id' => $order_id,
                );
            } catch (Exception $e) {
                Log::error("error", array("system" => "sce" ,"event" => "update_base_info", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("sce_error.order_update_error_1009");
                break;
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"event" => "update_insurance_date", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
   /*
     * 更改里程
     * */
    public function update_order_mileage(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'mileage' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $order_id = Input::get('order_id');
            $mileage = Input::get('mileage');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }

            Orders::where('order_id',$order_id)->update(array('mileage' => $mileage));

            $result = array(
                'order_id' => $order_id,
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce" ,"model" => "order", "event" => "update_order_mileage", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
}